import query from './atom/db/query';
import count from './atom/db/count';
import { IBaseTable } from './atom/db/interfaces';

declare const action_id: string;
declare const session_id: string;
declare const spaceid: string;

interface Message {
	filter: {};
	sort: {};
	page_size: number;
	page_no: number;
}

interface Exit_info extends IBaseTable {
    staff_no: string; 
    deptid: string; 
    _id:string;
    staff_name: string; 
	staff_type: string; 
	deptname: string; 
	destination: string; 
	to: string; 
	depart_time: number; 
	plan_time: number; 
	actual_time: number; 
	fund_source: string; 
	exit_port: string; 
	antry_port: string; 
	traffic_tool: string; 
}


function format(date: number) {
	if (date === null) {
		return '';
	}
	try {
		const _date = new Date(parseFloat(date + ''));
		if (_date) {
			return _date.getFullYear() + '-' + _format(_date.getMonth() + 1) + '-' + _format(_date.getDate());
		}
		return '';
	} catch (error) {
		return '';
	}
}

function _format(d: number) {
	if (d < 10) {
		return '0' + d;
	} else {
		return d;
	}
}

async function atom(msg: Message) {
	const systemid = '6051';
	const { exec, prepare } = query(action_id, session_id, spaceid, systemid);
	const asc: string[] = [];
	const desc: string[] = [];
	if (msg.sort) {
		const key = Object.keys(msg.sort)[0];
		if (msg.sort[key] === -1) {
			desc.push(key);
		} else {
			asc.push(key);
		}
	}
	// 证照信息
	prepare('Exit_info', ['staff_no','deptid','_id','staff_name','staff_type','deptname','destination','to','depart_time','plan_time','actual_time','fund_source','exit_port','antry_port','traffic_tool'], msg.filter, msg.page_size, msg.page_no, asc, desc);
	const [data] = await exec();

	data.forEach((item: Exit_info) => {
		item['depart_time_str'] = format(item.depart_time);
		item['plan_time_str'] = format(item.plan_time);
		item['actual_time_str'] = format(item.actual_time);
	});

	const c = count(action_id, session_id, spaceid, systemid);
	c.prepare('Exit_info', msg.filter);
	const [t] = await c.exec();

	return { dataArray: data, count: t };
}